import getConfig from '@/server/getConfig';
import { commonRequest } from '@/api/commonlist';
import zdd from 'gdt-jsapi';
import { getAppId } from '@/utils/local'; //
// import { setLocal } from '@/utils/utils';
import { dealLogin } from '@/api/login';
// import { loginLocal } from '@/api/login';

const [zddUrl, ddUrl] = ['govDing/freeLogin', 'dingTalk/dingLogin'];
const [zcUrl, dcUrl] = ['govDing/getTalk', 'dingTalk/get'];

export default {
  data() {
    return {
      proGress: '请求后台配置中...',
      loginError: false,
      errorMsg: '',
      url: {
        config: '', // 获取dd配置url
        login: '' // 登录接口
      },
      config: {}, // 外放配置
      dConfig: {} // 钉钉配置
    };
  },

  created() {
    this.initPage();
  },

  methods: {
    // 获取外放配置
    async getConfig() {
      let data = null;
      const config = await getConfig();
      if (config.data) {
        data = config.data;
        this.config = data;
        if (data.dType === 'zdd') {
          this.url.login = zddUrl;
          this.url.config = zcUrl;
        } else if (data.dType === 'dd') {
          this.url.login = ddUrl;
          this.url.config = dcUrl;
        }
      }
      return Promise.resolve(data);
    },

    async getdConfig(appId) {
      const dConfig = await commonRequest({
        app_Id: appId,
        appId
      }, this.url.config);

      if (!dConfig.success) {
        this.loginErrors(dConfig.message);
      }
      return Promise.resolve(dConfig.success && dConfig.data);
    },

    // 获取zdd免登授权码
    getFreeAuthorCode(config) {
      zdd.alert({ message: 'hello world!' });
    },

    // 开始zdd登录准备
    readyForZddLogin({ tenantId, app_Id }) {
      this.proGress = '请求钉钉登陆码中...';
      zdd.ready(() => {
        zdd.getAuthCode({
          corpId: tenantId
        }).then(
          (res) => { // 获取登录授权码
            const { code } = res;
            console.log(res, 'cqc');
            this.dLogin({ code, app_Id });
          },
          err => {
            this.loginErrors(err);
          }
        );
      });
    },

    // 登录
    dLogin({ code }) {
      this.proGress = '登陆中...';
      const appId = getAppId();
      const requestData = {
        corpId: code,
        app_Id: appId,
        appId: appId
      };
      const phone = this.$route.query.phone;

      if (phone) {
        requestData.telephone = phone;
      }

      commonRequest(requestData, this.url.login).then(res => {
        if (res.success) {
          this.dealLogin(res);
        } else {
          // loginLocal().then(res => this.dealLogin(res)); // ! 接口出现了问题。 写死
          this.dealLoginError(res); // 到时候放出来
        }
      });
    },

    // 登录失败
    dealLoginError(res) {
      const eventMap = {
        // 未绑定手机号
        1: () => {
          this.$router.replace('/404?phoneInput=1');
        },

        // 手机号验证错误
        2: () => {
          this.$router.replace('/404?errReg=1&phoneInput=1');
        },

        // 未分配角色，无权限
        3: () => {
          this.$router.replace('/404');
        }
      };

      if (res.data in eventMap) {
        eventMap[res.data]();
      } else {
        this.loginErrors(res.message + `, ${res.detail}`);
      }
    },

    // 登录成功
    dealLogin(res) {
      this.proGress = '登陆成功...';
      dealLogin(res);

      // setLocal([
      //   { token: res.token },
      //   { userName: data.trueName },
      //   { userTelephone: data.telephone },
      //   { userId: data.id + '' },
      //   { roleList: data.roleIdList[0].children },
      //   { appRole: data.roleIdList[0].children[0].name }
      // ]);

      setTimeout(() => {
        // if (window.history.length <= 1) {
        this.$router.push('/');
        // } else {
        // this.$router.go(-1);
        // }
      }, 1000);
    },

    loginErrors(msg) {
      this.loginError = true;
      this.errorMsg = msg;
    },

    async initPage() {
      const config = await this.getConfig();
      const dConfig = await this.getdConfig(getAppId());
      if (dConfig) {
        if (config.dType === 'zdd') {
          this.readyForZddLogin(dConfig);
        }
      }
    }
  }
};
